//
//  GWStatuseModel.m
//  新浪微博
//
//  Created by qianfeng on 16/1/15.
//  Copyright (c) 2016年 高炜. All rights reserved.
//

#import "GWStatuseModel.h"
#import "MJExtension.h"
#import "GWEmotionTool.h"
#import "NSDate+MJ.h"
#import "RegexKitLite.h"
#import "GWResultCaptur.h"
#import "GWEmotionAttachment.h"

@implementation GWStatuseModel
-(NSDictionary *)objectClassInArray
{
    return @{@"pic_urls":[GWPhotoModel class]};
}

/*
 "created_at" = "Fri Feb 19 14:24:00 +0800 2016"
 NSCalendar *calendar =[[NSCalendar alloc]init];
 //获得日期所有的元素
 [calendar components:<#(NSCalendarUnit)#> fromDate:createDate]
 fm.dateFormat =@"yyyy-MM-dd HH:mm:ss";
 */
//- (NSString *)created_at
//{
//
//    
////    _created_at =@"星期五 二月 19 17:09:55 +0800 2016";
//    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
//    //解析欧美格式时间时需把解析环境调整为英语
//    fmt.locale =[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
//    fmt.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
//    // 获得微博发布的具体时间
//    NSDate *createDate = [fmt dateFromString:_created_at];
//    
//    // 判断是否为今年
//    if (createDate.isThisYear) {
//        if (createDate.isToday) { // 今天
//            NSDateComponents *cmps = [createDate deltaWithNow];
//            if (cmps.hour >= 1) { // 至少是1小时前发的
//                return [NSString stringWithFormat:@"%ld小时前", cmps.hour];
//            } else if (cmps.minute >= 1) { // 1~59分钟之前发的
//                return [NSString stringWithFormat:@"%ld分钟前", cmps.minute];
//            } else { // 1分钟内发的
//                return @"刚刚";
//            }
//        } else if (createDate.isYesterday) { // 昨天
//            fmt.dateFormat = @"昨天 HH:mm";
//            return [fmt stringFromDate:createDate];
//        } else { // 至少是前天
//            fmt.dateFormat = @"MM-dd HH:mm";
//            return [fmt stringFromDate:createDate];
//        }
//    } else { // 非今年
//        fmt.dateFormat = @"yyyy-MM-dd";
//        return [fmt stringFromDate:createDate];
//    }
//}
/*
 /Mon Jan 25 09:23:18 +0800 2016 返回数据格式
 NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
 // 如果是真机调试，转换这种欧美时间，需要设置locale
 fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
 fmt.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
 // 设置日期格式（声明字符串里面每个数字和单词的含义）
 // E:星期几
 // M:月份
 // d:几号(这个月的第几天)
 // H:24小时制的小时
 // m:分钟
 // s:秒
 // y:年
 
 日期转为字符串
 fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
 fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
 _created_at = [fmt stringFromDate:createDate];
 
 */
-(NSString *)created_at
{
    
    NSDateFormatter *fm = [[NSDateFormatter alloc] init];
    fm.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
    //解析欧美格式时间时需把解析环境调整为英语 //中文环境zh_CN
    fm.locale =[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
    // 获得微博发布的具体时间
    NSDate *createDate =[fm dateFromString:_created_at];
    
   
    if (createDate.isThisYear) {//是今年的微博
        
        if ([createDate isToday]) {//今天
           NSDateComponents *components = [createDate deltaWithNow];
            if (components.hour>=1) {
                return [NSString stringWithFormat:@"%ld小时前",components.hour];
            }
            else if (components.minute>=1)
            {
                return [NSString stringWithFormat:@"%ld分钟前",components.minute];
            }
            else
            {
                return @"刚刚";
            }
        }
        else if ([createDate isYesterday])//昨天
        {
            fm.dateFormat =@"HH:mm";
            return [NSString stringWithFormat:@"昨天 %@",[fm stringFromDate:createDate]];
        }
        else//至少是前天
        {
            fm.dateFormat =@"MM-dd HH:mm";
            return [fm stringFromDate:createDate];
        }
        
    }
    else
    {
        fm.dateFormat =@"yyyy-MM-dd HH:mm";
        return @"刚刚";//[fm stringFromDate:createDate];
    }
}

//-(NSString *)source
//{
//    /*
//     source = "<a href=\"http://weibo.com/\" rel=\"nofollow\">\U5fae\U535a weibo.com</a>";
//     */
//    if (_source.length) {
//        
//        NSRange range;
//        range.location =[_source rangeOfString:@">"].location+1;
//        range.length =[_source rangeOfString:@"</"].location-range.location;
//        
//        return [NSString stringWithFormat:@"来自%@",[_source substringWithRange:range]];
//    }
//    return nil;
//}
-(void)setSource:(NSString *)source
{
    if (source.length) {
    NSRange range;
    range.location =[source rangeOfString:@">"].location+1;
    range.length =[source rangeOfString:@"</"].location-range.location;
    
    _source = [NSString stringWithFormat:@"来自%@",[source substringWithRange:range]];
    }
}

//排序好的分割完毕的字符串
-(NSArray *)sortResultCapturWithText:(NSString *)text
{
    NSMutableArray *resultArray =[NSMutableArray array];
    NSString *regexStr =@"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";
    [text enumerateStringsMatchedByRegex:regexStr usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
        GWResultCaptur *result =[[GWResultCaptur alloc]init];
        result.capturedStrings =*capturedStrings;
        result.capturedRanges =*capturedRanges;
        result.emotion =YES;
        [resultArray addObject:result];
    }];
    
    [text enumerateStringsSeparatedByRegex:regexStr usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
        GWResultCaptur *result =[[GWResultCaptur alloc]init];
        result.capturedStrings =*capturedStrings;
        result.capturedRanges =*capturedRanges;
        result.emotion =NO;
        [resultArray addObject:result];
    }];
    
    [resultArray sortUsingComparator:^NSComparisonResult(GWResultCaptur *obj1, GWResultCaptur *obj2) {
        NSInteger loc1 =obj1.capturedRanges.location;
        NSInteger loc2 =obj2.capturedRanges.location;
        return [@(loc1)compare:@(loc2)];
    }];
    return resultArray;
}
-(void)setUser:(GWUserModel *)user
{
    _user =user;
    [self createAttributedText];
}
-(void)setText:(NSString *)text
{
    _text =text;
    
    [self createAttributedText];
}
-(void)setRetweeted_status:(GWStatuseModel *)retweeted_status
{
    _retweeted_status =retweeted_status;
    self.retweeted =NO;
    _retweeted_status.retweeted =YES;
    
}
-(void)setRetweeted:(BOOL)retweeted
{
    _retweeted =retweeted;
    
    [self createAttributedText];
}
-(void)createAttributedText
{
    if (_text==nil||_user ==nil) return;
    if (_retweeted==YES) {
        NSString *text =[NSString stringWithFormat:@"@%@ : %@",_user.name,_text];
        _attributedText =[self attributedTextWithText:text];
    }
    else
    {
        _attributedText =[self attributedTextWithText:_text];
    }
}

-(NSAttributedString *)attributedTextWithText:(NSString *)text
{
    NSArray *resultArray =[self sortResultCapturWithText:text];
    
    NSMutableAttributedString *muAttStr =[[NSMutableAttributedString alloc]init];
    [resultArray enumerateObjectsUsingBlock:^(GWResultCaptur *obj, NSUInteger idx, BOOL *stop) {
        GWEmotion *emotion =nil;
        if (obj.isEmotion) {
            emotion =[GWEmotionTool emotionWitonDsec:obj.capturedStrings];
        }
        if (emotion) {
            
            GWEmotionAttachment *attach =[[GWEmotionAttachment alloc]init];
            attach.emotion =emotion;
            attach.bounds =CGRectMake(0, -3,  OriginalStatuseTextFont.lineHeight, OriginalStatuseTextFont.lineHeight);
            NSAttributedString *atStr =[NSAttributedString attributedStringWithAttachment:attach];
            [muAttStr appendAttributedString:atStr];
        }
        else
        {
            
            NSMutableAttributedString *atStr =[[NSMutableAttributedString alloc]initWithString:obj.capturedStrings];
            NSString *regexStr =@"@[a-zA-Z0-9\\u4e00-\\u9fa5]+ ?";
            [obj.capturedStrings enumerateStringsMatchedByRegex:regexStr usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
                [atStr addAttribute:NSForegroundColorAttributeName value:GWStatusHighTextColor range:*capturedRanges];
                [atStr addAttribute:GWStatuseLink value:*capturedStrings range:*capturedRanges];
            }];
            
            NSString *regexStr1 =@"#[a-zA-Z0-9\\u4e00-\\u9fa5]+#";
            [obj.capturedStrings enumerateStringsMatchedByRegex:regexStr1 usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
                [atStr addAttribute:NSForegroundColorAttributeName value:GWStatusHighTextColor range:*capturedRanges];
                [atStr addAttribute:GWStatuseLink value:*capturedStrings range:*capturedRanges];
            }];
            
            NSString *regexStr2 =@"http(s)?://([a-zA-Z|\\d]+\\.)+[a-zA-Z|\\d]+(/[a-zA-Z|\\d|\\-|\\+|_./?%&=]*)?";
            [obj.capturedStrings enumerateStringsMatchedByRegex:regexStr2 usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
                [atStr addAttribute:NSForegroundColorAttributeName value:GWStatusHighTextColor range:*capturedRanges];
                [atStr addAttribute:GWStatuseLink value:*capturedStrings range:*capturedRanges];
            }];
            [muAttStr appendAttributedString:atStr];
        }
    }];
    [muAttStr addAttributes:@{NSFontAttributeName:GWStatuseRichTextFont} range:NSMakeRange(0, muAttStr.length)];
    return muAttStr;
}

@end


@implementation GWUserModel
-(BOOL)isVip
{
    //是会员
    return self.mbtype>2;
}
@end


@implementation GWPhotoModel
-(void)setThumbnail_pic:(NSString *)thumbnail_pic
{
    _thumbnail_pic =thumbnail_pic;
    _bmiddle_pic =[_thumbnail_pic stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
}
@end
